package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsGoodsMapper;
import com.qf.pojo.*;
import com.qf.service.*;
import com.qf.util.AdminResponseCode;
import com.qf.util.AdminResponseUtil;
import com.qf.util.ResponseUtil;
import com.qf.vo.GoodsAllinone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DtsGoodsServiceImpl implements DtsGoodsService {

    @Autowired
    DtsGoodsMapper goodsMapper;

    @Autowired
    DtsCategoryService categoryService;

    @Autowired
    DtsGoodsAttributeService attributeService;

    @Autowired
    DtsGoodsSpecificationService specificationService;

    @Autowired
    DtsGoodsProductService productService;

    @Autowired
    DtsBrandService brandService;

    @Autowired
    DtsGoodsOrderService goodsOrderService;

    @Autowired
    DtsCartService cartService;

    @Override
    public Integer findTotal() {

        LambdaQueryWrapper<DtsGoods> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(DtsGoods::getDeleted, false);

        Integer count = goodsMapper.selectCount(wrapper);

        return count;
    }

    @Override
    public IPage<DtsGoods> queryPage(Integer page, Integer limit, String sort, String order, String goodsSn, String name, List<Integer> brandIds) {

        IPage<DtsGoods> iPage = new Page<>(page, limit);

        QueryWrapper<DtsGoods> wrapper = new QueryWrapper<>();

        if(!StringUtils.isEmpty(goodsSn)){
            wrapper.like("goods_sn", goodsSn);
        }

        if(!StringUtils.isEmpty(name)){
            wrapper.like("name", name);
        }

        if(brandIds != null && brandIds.size() > 0){
            wrapper.in("brand_id", brandIds);
        }

        if(order.equalsIgnoreCase("desc")){
            wrapper.orderByDesc(sort);
        }else {
            wrapper.orderByAsc(sort);
        }

        iPage = goodsMapper.selectPage(iPage, wrapper);

        return iPage;
    }

    @Override
    public Map<String, Object> findById(Integer id) {

        //先查询商品信息
        DtsGoods goods = goodsMapper.selectById(id);
        //查询商品的分类id（一级和二级）
        List<Integer> categoryIds = categoryService.findCategoryById(goods.getCategoryId());
        //查询商品的属性
        List<DtsGoodsAttribute> attributes = attributeService.findGoodsAttribute(id);
        //商品的规格
        List<DtsGoodsSpecification> specifications = specificationService.findGoodsSpecification(id);
        //商品的库存
        List<DtsGoodsProduct> products = productService.findGoodsProduct(id);

        Map<String, Object> data = new HashMap<>();
        data.put("categoryIds",categoryIds);
        data.put("goods",goods);
        data.put("attributes",attributes);
        data.put("specifications",specifications);
        data.put("products",products);

        return data;
    }

    @Override
    public Object update(GoodsAllinone goodsAllinone) {
        Object error = validate(goodsAllinone);
        //如果返回了错误消息
        if(error == null){
            return error;
        }

        DtsGoods goods = goodsAllinone.getGoods();
        DtsGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        DtsGoodsProduct[] products = goodsAllinone.getProducts();
        DtsGoodsAttribute[] attributes = goodsAllinone.getAttributes();

        //在修改前  判断是否在购物车  或者在订单表  如已存在  则不能修改
        int orderCnt = goodsOrderService.findCountByGid(goods.getId());
        int cartCnt = cartService.findCountByGid(goods.getId());
        if(orderCnt > 0 || cartCnt > 0){
            return AdminResponseUtil.fail(AdminResponseCode.GOODS_UPDATE_NOT_ALLOWED);
        }

        //更新数据库
        //更新商品基本信息
        goodsMapper.updateById(goods);
        //删除商品的属性
        attributeService.deleteByGid(goods.getId());
        //新增商品的属性
        for (DtsGoodsAttribute attribute : attributes) {
            attribute.setGoodsId(goods.getId());
            attributeService.insert(attribute);
        }
        //删除商品的规格
        specificationService.deleteByGid(goods.getId());
        //新增商品的规格
        for (DtsGoodsSpecification specification : specifications) {
            specificationService.insert(specification);
        }
        //删除商品的库存
        productService.deleteByGid(goods.getId());
        //新增商品的库存
        for (DtsGoodsProduct product : products) {
            productService.insert(product);
        }
        return ResponseUtil.ok();
    }

    @Override
    public void delete(Integer id) {
        attributeService.deleteByGid(id);
        productService.deleteByGid(id);
        specificationService.deleteByGid(id);
        goodsMapper.deleteById(id);
    }

    @Override
    public Object add(GoodsAllinone goodsAllinone) {

        Object error = this.validate(goodsAllinone);
        if (error != null){
            return error;
        }

        DtsGoods goods = goodsAllinone.getGoods();
        DtsGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        DtsGoodsProduct[] products = goodsAllinone.getProducts();
        DtsGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        //判断商品名称是否存在
        LambdaQueryWrapper<DtsGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsGoods::getName, goods.getName());
        Integer count = goodsMapper.selectCount(wrapper);
        if(count > 0){
            return AdminResponseUtil.fail(AdminResponseCode.GOODS_NAME_EXIST);
        }

        goods.setAddTime(new Date());
        goods.setUpdateTime(new Date());
        goods.setDeleted(false);
        goodsMapper.insert(goods);

        for (DtsGoodsAttribute attribute : attributes) {

            attribute.setGoodsId(goods.getId());
            attributeService.insert(attribute);
        }

        for (DtsGoodsProduct product : products) {

            product.setGoodsId(goods.getId());
            productService.insert(product);
        }

        for (DtsGoodsSpecification specification : specifications) {

            specification.setGoodsId(goods.getId());
            specificationService.insert(specification);
        }
        return ResponseUtil.ok();
    }

    private Object validate(GoodsAllinone goodsAllinone) {
        //获取商品基本信息
        DtsGoods goods = goodsAllinone.getGoods();

        if(goods == null){
            return ResponseUtil.badArgument();
        }

        if(StringUtils.isEmpty(goods.getName())||StringUtils.isEmpty(goods.getGoodsSn())){
            return AdminResponseUtil.fail(-1, "商品名称或编号不能为空");
        }

        Integer brandId = goods.getBrandId();

        if(brandId != null){
            boolean flag = brandService.isExists(brandId);
            if(!flag){
                return ResponseUtil.fail(-1, "品牌商不存在");
            }
        }

        //获取二级分类id
        Integer categoryId = goods.getCategoryId();

        if(categoryId != null){
            boolean flag = categoryService.isExists(categoryId);
            if(!flag){
                return ResponseUtil.fail(-1, "商品分类不存在");
            }
        }

        //获取商品的属性
        DtsGoodsAttribute[] attributes = goodsAllinone.getAttributes();

        if(attributes == null || attributes.length == 0){
            return ResponseUtil.fail(-1, "商品属性必须设置");
        }

        //获取商品的库存
        DtsGoodsProduct[] products = goodsAllinone.getProducts();

        if(products == null || products.length == 0){
            return ResponseUtil.fail(-1, "商品库存必须设置");
        }

        //获取商品的规格
        DtsGoodsSpecification[] specifications = goodsAllinone.getSpecifications();

        if(specifications == null || specifications.length == 0){
            return ResponseUtil.fail(-1, "商品规格必须设置");
        }

        return null;
    }
}
